﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Orderr;
using System;
using System.Collections.Generic;
using System.Linq;

namespace OrderWeb.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class OrderController : ControllerBase
    {
        private readonly OrderContext db;
        public OrderController(OrderContext context)
        {
            db = context;
        }
        [HttpGet("{id}")]
        public ActionResult<Order> GetOrder(int ID)
        {
            var order = db.Orders.Include(o => o.Details).ThenInclude(d => d.Good).FirstOrDefault(o => o.OrderID == ID);
            if (order == null) return NotFound();
            return order;
        }
        [HttpGet]
        public ActionResult<List<Order>> GetOrders(string customer)
        {
            var query = db.Orders.Include(o => o.Details).ThenInclude(d => d.Good).Where(o => true);
            if (customer != null) query = query.Where(o => o.Client.Name == customer);
            return query.ToList();
        }
        [HttpPost("add")]
        public ActionResult<Order> PostOrder(Order order)
        {
            foreach (var detail in order.Details)
            {
                detail.Good = null;
            }
            try
            {
                db.Orders.Add(order);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                return BadRequest(e.InnerException.Message);
            }
            return order;
        }
        [HttpPost("addGood")]
        public ActionResult<Good> PostOrderGood(Good good)
        {
            try
            {
                db.Goods.Add(good);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                return BadRequest(e.InnerException.Message);
            }
            return good;
        }
        [HttpPut("update")]
        public ActionResult<Order> PutOrder(Order order)
        {
            try
            {
                DeleteOrder(order.OrderID);
                PostOrder(order);
            }
            catch (Exception e)
            {
                return BadRequest(e.InnerException.Message);
            }
            return NoContent();
        }
        [HttpDelete("delete/{id}")]
        public ActionResult DeleteOrder(int ID)
        {
            try
            {
                var order = db.Orders.Include("Details").FirstOrDefault(o => o.OrderID == ID);
                if (order != null)
                {
                    db.Remove(order);
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                return BadRequest(e.InnerException.Message);
            }
            return NoContent();
        }
    }
}
